package cn.com.Servlet.CodeServlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CodeServlet",value = "/CodeServlet")
public class CodeServlet extends HttpServlet {

    //定义验证码的源码
    String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    //定义随机数
    Random random = new Random();

    //随机生成四个字符
    public String getCode(){
        String code = "";
        int len = str.length();
        for (int i = 0; i < 4 ; i++) {
            code += str.charAt(random.nextInt(len));
        }
        return code;
    }

    //获取随机颜色
    public Color getColor(){
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return new Color(red,green,blue);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取session
        HttpSession session = request.getSession();
        //生成验证码图片
        int width = 100;
        int height = 32;
        //画板
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //画笔
        Graphics pen = image.getGraphics();
        //矩形
        pen.fillRect(0,0,width,height);
        //字体
        pen.setFont(new Font("微软雅黑",Font.BOLD,20));
        //获取四个字符
        String code = getCode();
        //将验证码存入session
        session.setAttribute("imgcode",code);
        //绘制图片
        for (int i = 0; i < code.length(); i++) {
            //设置颜色
            pen.setColor(getColor());
            //一个一个画
            pen.drawString(String.valueOf(code.charAt(i)),i*15+15,25);
        }

        //通过response输出到页面
        ServletOutputStream outputStream = response.getOutputStream();
        //传输到客户端
        ImageIO.write(image,"png",outputStream);
        outputStream.flush();
        outputStream.close();

    }
}
